import { Button, Modal, Form, Input, message, Select, Table, Space } from 'antd';
import { addReason, getReason, changeOrderState,getOrderInfo,addOrderRefund } from '../../utils/cbt/sendRequset'
import { useState, useEffect, useContext } from 'react';
import MyContext from '../../utils/myContext'
import { refundStateMap,refundTypeMap } from './refundMap/refundMap'
import { mapBtn, mapState, mapChangeState, mapReBtn } from './orderManagment/pubData'
import { json } from 'react-router-dom';
const TableOrder = (props) => {
    const { cancleOrder, initData, changeData, getMsg } = props
    const store = useContext(MyContext)
    let [data, setData] = useState([]);
    //初始化页面所需数据
    useEffect(() => {
        getAllOrderInfo();
    }, []);
    //表头
    //获取所有表单数据
    const getAllOrderInfo = () => {
        getOrderInfo().then((res) => {
            if (res.code == 200) {
                console.log("后端请求返回来的数据", res);
                dealData(res);
            } else {
                console.log("resErr", res);
            }
        });
    }
    //公用的数据返回处理
    function dealData(res) {
        let arr = res.data;
        arr = arr.map((item) => {
            item.key = item.orderId;
            item.stateName = mapState.get(item.orState);
            item.btnName = mapBtn.get(item.orState);
            return item;
        });
        setData(arr);
    }
    // 点击选择确认返回id
    const confirmOrder = (record) => {
        store.selectReasonArr(record)
        const obj = JSON.parse(JSON.stringify(initData))
        obj.orderId = record.orderId
        console.log("选择的啥", obj);
        changeData(obj)
        cancleOrder()
    }
    const columns = [
        {
            title: "订单序号",
            dataIndex: "orderId",
            key: "orderId",
        },
        {
            title: "商品单价",
            dataIndex: "productPrice",
            key: "productPrice",
        },
        {
            title: "下单时间",
            dataIndex: "orStartTime",
            key: "orStartTime",
        },
        {
            title: "用户账号",
            dataIndex: "user_phone",
            key: "user_phone",
        },
        {
            title: "订单金额",
            dataIndex: "orPrice",
            key: "orPrice",
        },
        {
            title: "订单状态",
            dataIndex: "stateName",
            key: "stateName",
        },
        {
            title: "操作",
            key: "action",
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => confirmOrder(record)}>
                        选择
                    </a>
                </Space>
            ),
        },
    ];
    // 勾选的数组
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            //selectedRowKeys as id,selectedRows as data
            setSelectArr(selectedRowKeys);
        },
    };
    return (
        <>
            <Table rowSelection={{
                type: 'checkbox',
                ...rowSelection,
            }} columns={columns} dataSource={data}
                pagination={{
                    pageSize: 4
                }} />
        </>
    );
}


const Add = (props) => {
    const [reasonArr, setReasonArr] = useState([])
    const [openOrder, setOpenOrder] = useState(false)
    const [initData, setInitData] = useState({ orderId: '', reason: '' })
    const store = useContext(MyContext)
    useEffect(() => {
        getReasonArr()
        console.log("下拉雷匡原因", reasonArr);
    }, [])
    const getReasonArr = () => {
        getReason().then(res => {
            if (res.code == 200) {
                const tableData = res.data
                store.serReasonArr(tableData)
                // setReasonArr(tableData)

            }

        })
    }
    const { open, cancleBtn, getMsg, state } = props
    console.log("进入的添加", state);
    const tailLayout = {
        wrapperCol: {
            offset: 17,
            span: 20,
        },
    };
    const onFinish = (values) => {
        const obj = {}
        obj.orderId = initData.orderId
        values.orderId = initData.orderId
        values.create_time = (new Date()).Format("yyyy-MM-dd HH:mm:ss")
        values.key_user_id = store.checkOrder.user_id//申请人id
        values.deal_type = state//类型
        values.refund_money = store.checkOrder.orPrice//退款金额 
        addOrderRefund(values).then(res => {
            console.log("点击添加", res);
            if (res.code == 200) {
                getMsg()
                changeOrderState(obj).then(res => {
                    if (res.code == 200) {
                        message.success('添加成功')
                    }
                })
            } else {
                message.error('添加失败')
            }
        })
        cancleBtn()
    };
    const handleCancel = () => {
        cancleBtn();
    };
    // 选择订单的模态框
    const checkOrder = () => {
        console.log('点击了');
        setOpenOrder(true)
    }
    const handleCancelOrder = () => {
        setOpenOrder(false)
    }
    // 改变表单渲染初始值
    const changeData = (newData) => {
        setInitData(newData)
    }
    return (
        <>
            {/* 添加的弹框 */}
            <Modal
                title="退货/退款添加"
                open={open}
                footer={null}
                onCancel={handleCancel}
                destroyOnClose='true'
            >
                <Form
                    name="basic"
                    labelCol={{
                        flex: '80px',
                    }}
                    labelAlign="left"
                    labelWrap
                    wrapperCol={{
                        flex: 1,
                    }}
                    colon={false}
                    initialValues={initData}
                    preserve={false}
                    onFinish={onFinish}
                >
                    <Form.Item
                        label="订单"
                        name="orderId"
                    >
                        {
                            initData.orderId != '' ?
                                <>
                                    <p>
                                        <span style={{ marginRight: '2rem' }}>{initData.orderId}</span>
                                        <a onClick={checkOrder} >更改订单</a>
                                    </p>
                                </>

                                : <a onClick={checkOrder}>请选择订单</a>
                        }

                    </Form.Item>
                    <Form.Item
                        label="原因"
                        name="reason"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    >
                        <Select>
                            {
                                store.reasonArr.map((item, index) => (<Select.Option value={item.reason} key={item.id}>{item.reason} </Select.Option>))
                            }


                        </Select>
                    </Form.Item>
                    <Form.Item {...tailLayout}>
                        <Button htmlType="button" onClick={handleCancel}>
                            取消
                        </Button>
                        <Button type="primary" htmlType="submit" style={{ marginLeft: '10px' }}>
                            确认
                        </Button>
                    </Form.Item>

                </Form>
            </Modal >
            {/* 选择订单的弹框 */}
            <Modal
                title="请选择订单"
                open={openOrder}
                // footer={null}
                onCancel={handleCancelOrder}
                destroyOnClose='true'
            >
                <div>
                    <TableOrder cancleOrder={handleCancelOrder} initData={initData} changeData={changeData}></TableOrder>
                </div>
            </Modal >
        </>
    );
};
export default Add;